package com.dtn.wsn.middleware;
/**
 * 
 * HttpsqsMessageHandler is to analyze and 
 * process the httpsqs message. 
 * 
 */
import com.dtn.wsn.dao.CollectionHistoryDAO;
import com.dtn.wsn.dao.TableManager;
import com.dtn.wsn.database.ConnectionPool;
import com.dtn.wsn.demo.WSNApplication;
import com.dtn.wsn.sunspot.DataCollector;
import com.dtn.wsn.sunspot.SunspotConnectionManager;
import com.sun.spot.io.j2me.radiogram.RadiogramConnection;
import java.util.logging.Level;
import java.util.logging.Logger;


public class HttpsqsMessageHandler {

    public HttpsqsMessageHandler() {
    }

    /**
     * Handle the message
     * @param message
     * @return int ret_val 0 successfully, 1 retry, 2 Dead
     */
    public int handle(String message) {

        int ret_val = 0;
        //                  [0]  [1]     [2]    [3]        [4]
        //message format: start  67    10000   60000     1322752161
        //          para  action port  timeout  duration   timestamp
        if (message.startsWith("START")) {
            String para[] = message.split(" ");
            //
            try {
                WSNApplication wa = new WSNApplication(Integer.parseInt(para[1]));

                SunspotConnectionManager scm = wa.getSunspotConnectionManager();

                RadiogramConnection rcon = scm.getRadiogramConnection();
                //after get the connection, we set the connection timeout
                rcon.setTimeout(Integer.parseInt(para[2]));


                ConnectionPool connPool = wa.getConnectionPool();
                DataCollector dc = new DataCollector(rcon, connPool);
                //set the sample duration
                dc.setSampling_duration(Integer.parseInt(para[3]));
                int sampleCnt = dc.collectData();

                //update the status
                CollectionHistoryDAO chDao = new CollectionHistoryDAO(connPool);
                String status;
                if (sampleCnt == 0) {
                    status = "DEAD";
                    //Actually, here it should retry for one more time.
                    //but since the task is time-critical thus, we put the dead queue directly for manual operation.
                    ret_val = 2;
                } else {
                    status = "Collected " + sampleCnt + " samples.";
                }
                int updateReturn = chDao.updateStatusByTimestample(para[4], status);
                if (updateReturn == 0) {
                    System.out.println("EERO in update the status");
                    ret_val = 2;
                }

                wa.TearDownWSNApplication();
            } catch (Exception ex) {
                Logger.getLogger(HttpsqsMessageHandler.class.getName()).log(Level.SEVERE, null, ex);
                ret_val = 2;
            }

        } else if (message.startsWith("db-init")) {
            String para[] = message.split(" ");

            try {
                ConnectionPool connPool = new ConnectionPool("com.mysql.jdbc.Driver",
                        "jdbc:mysql://localhost:3306/wsn", "root", "bytewalla5");
                connPool.createPool();
                TableManager tm = new TableManager(connPool);
                for(int i = 1; i<para.length;i++){
                    tm.reInitTable(para[i]);
                }
                
                connPool.closeConnectionPool();

            } catch (Exception ex) {
                Logger.getLogger(HttpsqsMessageHandler.class.getName()).log(Level.SEVERE, null, ex);
            }


        }
        return ret_val;
    }
}
